package top.infopub.mgc.core.sender.email;


import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.infopub.common.ErrorCodeEnum;
import top.infopub.mgc.core.domain.PartnerInfoDomain;
import top.infopub.mgc.core.service.PartnerInfoService;
import top.infopub.mgc.util.EnviornConfig;
import top.infopub.model.mgc.MsgTask;
import top.infopub.vo.ResponseVo;


/**
 * 邮件发送工具类
 * @author Awoke
 * @version 2018年11月7日
 * @see EmailSender
 * @since
 */
@Component
public class EmailSender {

    private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);

    @Resource
    private EnviornConfig env;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /** partner-code **/
    private static final String PARTNER_CODE_EMAIL = "MGC_PARTNER_EMAIL";

    /**
     * 发送邮件 <br/>
     * 支持多收件人、多抄送人、多附件
     * @param msgTask
     * @throws Exception 
     * @see
     */
    @SuppressWarnings("unchecked")
    public ResponseVo<String> sendMail(MsgTask msgTask) {
        if (!env.isProduction()) {
            return ResponseVo.getSuccessResponse();
        }
        try {
            PartnerInfoDomain partnerInfo = partnerInfoService.getPartnerCache(PARTNER_CODE_EMAIL);
            PartnerInfoDomain.Email emailInfo = partnerInfo.getEmail();

            HtmlEmail email = new HtmlEmail();
            email.setCharset("UTF-8");
            email.setHostName(emailInfo.getHost());
            // 阿里云ECS为管控垃圾邮件，屏蔽了25端口号的服务，所以导致该访问超时，尝试使用ssl方式的465端口
            email.setSmtpPort(465);
            email.setSSLOnConnect(true);
            
            email.setAuthentication(partnerInfo.getSpartnerAccName(),
                partnerInfo.getSpartnerAccPassword());
            email.setFrom(emailInfo.getFrom(), emailInfo.getFromName());

            String emailTo = msgTask.getMsgRecipient();
            if (StringUtils.contains(emailTo, ",")) { // 多个收件人
                email.addTo(emailTo.split(","));
            }
            else { // 单个收件人      
                email.addTo(emailTo);
            }
            String emailCc = msgTask.getMsgCc();
            if (StringUtils.contains(emailCc, ",")) { // 多个抄送人
                email.addCc(emailCc.split(","));
            }
            else if (StringUtils.isNotBlank(emailCc)) { // 单个抄送人    
                email.addCc(emailCc);
            }
            email.setSubject(msgTask.getTitle());
            email.setHtmlMsg(msgTask.getContent());
            // 添加附件
            if (!StringUtils.isEmpty(msgTask.getAttach())) {
                String[] attStrs = msgTask.getAttach().split(",");
                for (String attStr : attStrs) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(attStr);
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    email.attach(attachment);
                }
            }
            // send
            email.send();
            return ResponseVo.getSuccessResponse();
        }
        catch (Exception e) {
            logger.error("sendMail error", e);
            return ErrorCodeEnum.ERROR_MGC_SENDMAIL.getResponseVo(e.getClass().getName() + " "
                                                                 + e.getMessage());
        }
    }

}
